package com.example.Hongbao;

import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.provider.Settings;
import android.util.Log;
import android.view.accessibility.AccessibilityManager;
import android.widget.Toast;

import java.util.Iterator;
import java.util.List;

/**
 * Created by Fcy on 2015/12/24.<br/>
 */
public class UpdateManager
{
	/**
	 * 前往设置打开服务
	 * 
	 * @param context
	 */
	public static void openServer(Context context, String serverName)
	{
		try
		{ // 打开系统设置中辅助功能
			Intent killIntent = new Intent(
			        Settings.ACTION_ACCESSIBILITY_SETTINGS);
			context.startActivity(killIntent);
			Toast.makeText(context, String.format("找到%s，然后开启服务即可", serverName),
			        Toast.LENGTH_LONG).show();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 下载完成调用该方法，开始自动安装升级包（会先尽兴检查是否满足条件）
	 */
	public static void startUpdate(final Context context)
	{
		// 如果sd卡里没有升级包，就不再启动update.apk
//		if (!FileUtils.isUpdateExists(Constants.UPDATE_FILE_NAME))
		if (!FileUtils.isUpdateExists("trinea.apk"))
		{
			MyApplication.getInstance().isOpen = false;
			// fixme 为了测试使用
			Toast.makeText(context, "没有找到升级包", Toast.LENGTH_SHORT).show();
			return;
		}

		// 先检查服务是否开启
		if (!isAccessibilityEnabled(context))
		{ // 禁止dialog点击外面消失
			new AlertDialog.Builder(context)
			        .setMessage("服务暂未开启，您必须开启服务后才能使用。\n找到%s，然后开启服务即可")
			        .setTitle("请开启服务").setPositiveButton("前往开启",
			                new DialogInterface.OnClickListener()
			                {
				                @Override
				                public void onClick(DialogInterface dialog,
			                            int which)
				                {
					                openServer(context, "");
				                }
			                })
			        .show().setCanceledOnTouchOutside(false);
			return;
		}

		// 显示弹窗
		FloatWindowServiceManager
		        .getInstance(MyApplication.getInstance().getApplicationContext())
		        .showWindow();
		// 启动app com.android.updater:id/more_btn
		startAppByPackageName(context, "com.android.updater");
	}

	private static boolean DEBUG = false;

	private static String TAG = "AccessibilityManager";

	/*
	 * Check Accessibility Setting, IF NOT enabled, Notice User To Enable
	 *
	 */
	public static boolean isAccessibilityEnabled(Context paraContext)
	{
		Log.i(TAG, "Enter isAccessibilityEnabled");
		if (paraContext == null)
		{
			Log.e(TAG, "isAccessibilityEnabled paraContext Null");
			return false;
		}
		AccessibilityManager accessibilityManager = (AccessibilityManager) paraContext
		        .getSystemService(Context.ACCESSIBILITY_SERVICE);
		if (accessibilityManager == null)
		{
			Log.e(TAG, "Accessibility service Null");
			return false;
		}
		String selfPackageName = paraContext.getPackageName();

		// TODO: 可以monitor服务状态变化，以及时启动服务
		// API Level 18, Do not use
		// accessibilityManager.addTouchExplorationStateChangeListener(listener);

		// Get Enabled services
		// Sometimes, even settings display checked, But in fact the service is
		// not enabled(maybe APP changed)
		List<AccessibilityServiceInfo> enableList = accessibilityManager
		        .getEnabledAccessibilityServiceList(
		                AccessibilityServiceInfo.FEEDBACK_GENERIC);

		if (enableList == null)
		{
			if (DEBUG)
			{
				Log.w(TAG, "Accessibility Service Not enabled");
			}
			/*
			 * 2015-4-8：调用者发送变化，会循环进行判断，因此不再上报信息
			 * Analytics.analyticsOnEvent(paraContext,
			 * Analytics.FIAL_AS_NOT_ENABLE);
			 */
			return false;
		}
		Iterator<AccessibilityServiceInfo> iterator = enableList.iterator();
		while (iterator.hasNext())
		{
			AccessibilityServiceInfo asInfo = (AccessibilityServiceInfo) iterator
			        .next();
			if (asInfo.getResolveInfo() == null)
			{
				if (DEBUG)
				{
					Log.w(TAG, "getResolveInfo NULL");
				}
				continue;
			}
			if (selfPackageName.equalsIgnoreCase(
			        asInfo.getResolveInfo().serviceInfo.packageName))
			{
				return true;
			}
			else
			{
				/*
				 * 2015-4-8：调用者发送变化，会循环进行判断，因此不再上报信息 Map<String, String>
				 * enableAs = new HashMap<String, String>();
				 * enableAs.put("enabled",
				 * asInfo.getResolveInfo().serviceInfo.packageName);
				 * Analytics.analyticsOnEvent(paraContext,
				 * Analytics.ENABLED_ACCESSIBILITY_SERVICE, enableAs);
				 */
			}
		}
		if (DEBUG)
		{
			Log.w(TAG, "Accessibility Service Not enabled");
		}
		/*
		 * 2015-4-8：调用者发送变化，会循环进行判断，因此不再上报信息
		 * Analytics.analyticsOnEvent(paraContext,
		 * Analytics.FIAL_AS_NOT_ENABLE);
		 */
		return false;
	}

	/**
	 * 通过包名启动app
	 * 
	 * @param context
	 * @param packagename
	 */
	public static void startAppByPackageName(Context context,
	        String packagename)
	{
		// 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
		PackageInfo packageinfo = null;
		try
		{
			packageinfo = context.getPackageManager()
			        .getPackageInfo(packagename, 0);
		} catch (PackageManager.NameNotFoundException e)
		{
			e.printStackTrace();
		}
		if (packageinfo == null)
		{
			return;
		}

		// 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
		Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
		resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		resolveIntent.setPackage(packageinfo.packageName);

		// 通过getPackageManager()的queryIntentActivities方法遍历
		List<ResolveInfo> resolveinfoList = context.getPackageManager()
		        .queryIntentActivities(resolveIntent, 0);

		ResolveInfo resolveinfo = resolveinfoList.iterator().next();
		if (resolveinfo != null)
		{
			// packagename = 参数packname
			String packageName = resolveinfo.activityInfo.packageName;
			// 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
			String className = resolveinfo.activityInfo.name;
			// LAUNCHER Intent
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);

			// 设置ComponentName参数1:packagename参数2:MainActivity路径
			ComponentName cn = new ComponentName(packageName, className);

			intent.setComponent(cn);
			context.startActivity(intent);
		}
	}
}
